import { message } from 'antd';

/**
 * @description 为原始数据设置id
 * @param originData 原始数据
 * @returns
 */
export const getRawData = (originData: any) => {
  let identifier = 1;
  // 设置闭包，每个审批流数据设置的id都从1开始计数；
  const fun = (data: any) => {
    const item = {
      ...data
    };

    if(item?.subSteps?.length && !item.next){
      message.error('The structure of data has changed!');
    }

    if(!item.identifier){
      item.identifier = `${identifier}`;
      identifier += 1;
    }

    if(item?.next) {
      item.next = fun(item.next);
    }

    if(Array.isArray(item?.subSteps)){
      item.subSteps = item.subSteps.map(fun)
    }
    return item;
  }
  return fun(originData);
}

const getNodes = (raw: any, list = []) => {
  let arr = [...list] as any;
  if(raw?.subSteps?.length){
    raw.subSteps.forEach((item: any) => {
      arr = getNodes(item, arr);
    });
  } else {
    arr.push(raw)
  }
  if(raw.next){
    arr = getNodes(raw.next, arr);
  }
  return arr;
}

const getEdges = (raw: any, list = [], posterityNode?: any) => {
  let arr = [...list] as any;

  if(raw?.next?.subSteps?.length){
    // 流程分叉
    arr = getEdges(raw.next?.next, arr);
    raw.next.subSteps.forEach((item: any) => {
      arr.push({
        source: raw,
        target: item
      });
      arr = getEdges(item, arr, raw.next?.next);
    });
  }else if(raw.next){
    arr.push({
      source: raw,
      target: raw.next
    })
    arr = getEdges(raw.next, arr, posterityNode);
  }else if(posterityNode){
    arr.push({
      source: raw,
      target: posterityNode
    })
  }
  return arr;
}

export const extract = (raw: any) => {
  const nodes = getNodes(raw);
  const edges = getEdges(raw);

  return {
    nodes,
    edges
  }
}

// 判断当前节点是否完成审批:
export const isDeal = (data: any) => data?.units?.some?.((unit: any) => unit.dealDate !== null);

// 获取当前进行的审批节点
export const getCurrentApprove = (options: any = {}) => {
  const { loginUser, nodes, edges, isApproved = isDeal, isApprover, mustVerifyApprover } = options;
  if(loginUser || isApprover) {
    // 当前审批的流程节点
    const currentNodes = [];
    if(!isApproved?.(nodes[0])) {
      // 第一个节点如果没有完成审批，子节点必定没有完成审批
      currentNodes.push(nodes[0]);
    }else {
      edges.forEach(({ source, target }: {source: any, target: any }) => {
        // 父流程已经完成审批，子流程没有完成，表示当前子流程审批中：
        if(isApproved?.(source) && !isApproved?.(target)){
          currentNodes.push(target);
        }
      });
    }
    return (
      currentNodes?.find((item: any) => {
        if(typeof isApprover === 'function'){
          return isApprover(item);
        }
        return item?.units?.some?.((unit: any) => unit?.user === loginUser);
      }) ?? (mustVerifyApprover ? undefined : currentNodes[0])
    )
  }
  return undefined;
}
